﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ZapHelper
{
    public class GenericCategoryParser : CategoryParser
    {

        #region Properties
        
        public IEnumerable<CategoryParser> CategoryParsers { get; private set; }

        public IEnumerable<CategoryParser> DefaultCategoryParsers
        {
            get
            {
                yield return new JavaScriptCategoryParser();
                yield return new AHrefCategoryParser();
                yield return new ProductsOnlyCategoryParser();
            }
        }

        #endregion

        #region Methods

        #region Instance



        public GenericCategoryParser(
            IEnumerable<CategoryParser> categoryParsers = null)
        {
            if (categoryParsers == null)
            {
                categoryParsers = DefaultCategoryParsers;
            }

            CategoryParsers = categoryParsers;
        }

        #endregion

        /// <summary>
        /// Pass each implemented CategoryParser and try to return his categories
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        protected override IEnumerable<Category> ParseCaterories()
        {
            var categoriesList = new List<Category>();

            foreach (var categoryParser in CategoryParsers)
            {
                IEnumerable<Category> categories;
                try
                {
                    categoryParser.ReloadFromCategoryParser(this);
                    categories = categoryParser.Categories;
                    categoriesList.AddRange(categories);
                }
                catch (ParseFailedException)
                {
                    continue;
                }
            }

            return categoriesList;
        } 

        #endregion
    }
}
